<?php
/**
 *APINAME:
 *Developer:
 *Complete:
 */

namespace app\index\controller;


use app\index\common\BaseController;
use app\index\model\User;
use app\index\validate\Vali;
use think\facade\Cache;
use think\facade\Request;

class Login extends BaseController
{
    /**
     * 注册接口
     * @param Vali $validate
     * @param User $user
     * @return \think\response\Json
     */
    public function register(Vali $validate , User $user){
        $data = Request::param();                       //获取前端提交的所有信息
        if (!$validate->scene('register')->batch()->check($data)) return $this->returnJson(self::ERROR,'数据格式不正确',$validate->getError());   //验证数据格式
        $result = $user->where('userName','=',$data['userName'])->find();
        if ($result)  return $this->returnJson(self::ERROR,'该用户已经注册了');         //判断用户是否存在
        $data['password']  =  md5($data['password']);           //加密密码
        if (!$user->save($data)) return $this->returnJson(self::ERROR,'数据库错误');             //判断是否插入数据库中
        return $this->returnJson(self::OK,'注册成功');
    }

    /**
     * 登录接口
     * @param User $user
     * @return \think\response\Json
     */
    public function login(User $user){
        $data = Request::param();                   //获取前端提交的所有信息
        $result = $user->where('userName','=',$data['userName'])->find();
        if (!$result)  return $this->returnJson(self::ERROR,'该用户未注册或输入错误');         //判断用户是否存在
        if (md5($data['password'])  !=  $result['password']) return $this->returnJson(self::ERROR,'密码错误');
        return $this->returnJson(self::OK,'登录成功',['token' => $this->createToken($result) , 'role' => $result['role']]);
    }

    /**
     * 退出登录接口
     * @return \think\response\Json
     */
    public function exitLogin(){
        $token = Request::header('Authorization');
        Cache::rm($token);
        return $this->returnJson(self::OK,'退出登录成功');
    }

    /**
     * 创建Token
     * @param $userMsg
     * @return string
     */
    public function createToken($userMsg){
        $token = md5(md5($userMsg['id']) . md5($userMsg['role'] . rand(0,9999)));
        Cache::set($token,['id' => $userMsg['id'] , 'role' => $userMsg['role']],60*60*24);
        return $token;
    }

}